package user_api

import (
	"fastgin/global"
	"fastgin/middleware"
	"fastgin/models"
	"fastgin/utils/pwd"
	"fastgin/utils/res"
	"fmt"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

type CreateUserRequest struct {
	Username string `json:"username" binding:"required" label:"用户名"`
	Nickname string `json:"nickname"`
	Passwd   string `json:"passwd" binding:"required" label:"密码"`
	RoleID   int8   `json:"roleID" binding:"required" label:"角色"`
}

func (UserApi) CreateUserView(c *gin.Context) {
	// 获取绑定的 JSON 数据
	cr := middleware.GetBind[CreateUserRequest](c)
	var user models.UserModel
	count := global.DB.Where("username=?", cr.Username).Take(&user).RowsAffected
	if count != 0 {
		logrus.Errorf(fmt.Sprintf("%s 账号已存在", cr.Username))
		res.FailWithMsg("账号已存在", c)
		return
	}
	hashPwd := pwd.GenerateFromPassword(cr.Passwd)
	err := global.DB.Create(&models.UserModel{
		Username: cr.Username,
		Passwd:   hashPwd,
		Nickname: cr.Nickname,
		RoleID:   cr.RoleID,
	}).Error
	if err != nil {
		logrus.Errorf("用户%s创建失败", cr.Username)
		res.FailWithMsg("用户创建失败", c)
		return
	}
	logrus.Infof("用户%s创建成功", cr.Username)
	res.OkWithData(map[string]interface{}{
		"username": cr.Username,
		"nickname": cr.Nickname,
		"roleID":   cr.RoleID,
	}, c)
	return
}
